package esim.service.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import esim.service.domain.Invoice;
import esim.service.entity.*;
import esim.service.service.InvoiceService;
import esim.service.service.OrderService;
import esim.service.supports.CloudUserUtils;
import esim.service.supports.InstanceProperty;
import esim.service.supports.ShdzfpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sajt.shdzfp.bean.Data;
import sajt.shdzfp.bean.GlobalInfo;
import sajt.shdzfp.bean.ReturnStateInfo;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.ExecutionException;

/**
 * @Author: wbb
 * @Date: 2021/4/19 18:46
 */
@Slf4j
@RestController
@RequestMapping("/invoice")
public class InvoiceController {
    private final InvoiceService invoiceService;

    private final OrderService orderService;

    @Resource
    private InstanceProperty instanceProperty;

    public InvoiceController(InvoiceService invoiceService,OrderService orderService) {
        this.invoiceService = invoiceService;
        this.orderService = orderService;
    }

    /**
     * 开具发票，充值平台使用
     * @param info 开票信息
     */
    @PostMapping("/create")
    public Response<String> createInvoice(@Valid @RequestBody InvoiceInfo info) {
        log.info("开具发票: {}", JSON.toJSONString(info));
        invoiceService.create(info, CloudUserUtils.getUserId());
        return Response.from("发票开具请求已接收,请等待发票下载完成", HttpStatus.OK.value());
    }

    /**
     * 获取pdf发票下载的url，充值平台使用
     * @param invoiceId 发票id
     * @return pdf发票下载的url
     */
    @GetMapping("/download/{invoiceId:\\d+}")
    public Response<String> loadPdfUrl(@PathVariable Integer invoiceId) {
        String pdf = invoiceService.loadPdfUrl(invoiceId, CloudUserUtils.getUserId());
        return Response.from(pdf);
    }
    //开票历史(app)
    @GetMapping("/invoices")
    public Response<Object> historys() {
        return Response.from(invoiceService.historys(CloudUserUtils.getUserId()));
    }

    //开票历史(web)
    @PostMapping("/data")
    public Response<Object> data(@RequestBody Query<Invoice> query) {
        return Response.from(invoiceService.query(query));
    }

    @PostMapping("/resend/{invoiceId:\\d+}")
    public Response<String> resend(@PathVariable Integer invoiceId, @RequestParam String email){
        log.info("重发发票:{}", invoiceId);
        boolean result = invoiceService.resend(invoiceId, email);
        return Response.from(result?"发送成功":"发送失败", result?HttpStatus.OK.value():500);
    }

    @PostMapping("/detail/{invoiceId:\\d+}")
    public Response<InvoiceDetail> resend(@PathVariable Integer invoiceId){
        return Response.from(invoiceService.invoceDetail(invoiceId));
    }

    @PostMapping(value = "/ECXML_FPKJJG_TS_E_INV",produces= MediaType.APPLICATION_XML_VALUE, consumes=MediaType.APPLICATION_XML_VALUE)
    public FpResponse ECXML_FPKJJG_TS_E_INV(@RequestBody InvoceBody body) {
        log.info("收到发票平台推送数据 {}", JSONObject.toJSONString(body));
        InvoceBody.RESPONSE_FPMXXZ fpmxxz = body.getResponse_fpmxxz();
        try {
            this.invoiceService.push(body).get();
            String returnCode = "0000";
            FpResponse fpResponse = new FpResponse();
            GlobalInfo globalInfo = ShdzfpUtils.createGlobalInfo(instanceProperty.getShdzfp(),fpmxxz.getFpqqlsh(),"ECXML.FPKJJG.TS.E_INV");
            Data data = ShdzfpUtils.createData();
            data.setContent("");
            ReturnStateInfo returnStateInfo = ShdzfpUtils.createReturnStateInfo(returnCode,"");
            fpResponse.setGlobalInfo(globalInfo);
            fpResponse.setData(data);
            fpResponse.setReturnStateInfo(returnStateInfo);
            return fpResponse;
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

}
